import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import { cascadersSource } from '@/services/api/api-monitor-source';
import {
  pageMonitorVideo,
  pageMonitorVideoRecordStatistics,
} from '@/services/api/api-monitor-video';
import type { ActionType, FormInstance, ProColumns } from '@ant-design/pro-components';
import {
  PageContainer,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormRadio,
  ProFormSwitch,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Cascader, Descriptions, Flex } from 'antd';
import moment from 'moment';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
import DetailMonitorVideo from './DetailMonitorVideo';
interface PageContainerMonitorVideoProps {}

const PageContainerMonitorVideo: React.FC<PageContainerMonitorVideoProps> = (props) => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [cascadersSourceData, setCascadersSourceDataState] = useState<
    MonitorData.CascadersSource[]
  >([]);

  const [optionsCascadersSourceData, setOptionsCascadersSourceDataState] = useState<
    MonitorData.CascadersSource[]
  >([]);

  const [pageMonitorVideoRecordStatisticsData, setPageMonitorVideoRecordStatisticsDataState] =
    useState<MonitorVideoData.VideoRecordPageStatistics[]>([]);

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  const columns: ProColumns<MonitorVideoData.VideoRecordPage>[] = [
    {
      title: '标题',
      dataIndex: 'content',
      width: '650px',
      hideInSearch: true,
      ellipsis: true,
      render: (dom, row) => (
        <DetailMonitorVideo
          data={row}
          onRefurbish={() => {
            actionRef.current?.reload();
          }}
        />
      ),
    },
    {
      title: '账号',
      key: 'source',
      dataIndex: 'sourceName',
      width: 230,
      render: (dom, row) => (
        <Flex align="center" justify="left" gap="small">
          {row.sourceChannelName == '抖音' ? (
            <IconDouyin width={20} height={20} />
          ) : (
            <IconKuaishou width={20} height={20} />
          )}
          {row.sourceName}
        </Flex>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'releaseTime',
      key: 'dates',
      width: '180px',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'articleUrl',
      key: 'articleUrl',
      width: '120px',
      align: 'center',
      search: false,
      render: (dom, entity, index, action, schema) => (
        <a href={entity?.sourceUrl} target="_blank">
          查看原文
        </a>
      ),
    },
  ];

  const getCascadersSource = () => {
    const channelIds = new Array();
    const levelIds = new Array();

    let channelId = formRef.current?.getFieldValue('channelId');
    let levelId = formRef.current?.getFieldValue('levelId');

    if (channelId == 'clean' || levelId == 'clean') {
      return;
    }

    if (channelId == 'all') {
      channelIds.push('8117112414994505', '8117112416043075');
    } else {
      channelIds.push(channelId);
    }

    if (levelId == 'all') {
      levelIds.push('2000', '3000');
    } else {
      levelIds.push(levelId);
    }

    let showCascadersData = new Array();

    cascadersSourceData.forEach((level) => {
      if (levelIds.includes(level.value)) {
        const showAreaData = new Array();

        const levelData = { ...level };

        level.children.forEach((area) => {
          const sources = new Array();

          let areaData = { ...area };

          area.children
            .filter((source) => channelIds.includes(source.channelId))
            .forEach((source) => {
              sources.push({
                label: `${source.label} (${source.channelName})`,
                value: source.value,
                channelId: source.channelId,
                channelName: source.channelName,
              });
            });

          if (sources.length > 0) {
            areaData.children = sources;
            showAreaData.push(areaData);
          }
        });

        if (showAreaData.length > 0) {
          levelData.children = showAreaData;
          showCascadersData.push(levelData);
        }
      }
    });

    setOptionsCascadersSourceDataState(showCascadersData);
  };

  const loadCascadersSource = async () => {
    const response = await cascadersSource();
    if (response.code == 0) {
      setCascadersSourceDataState(response.data);
    }
  };

  const loadPageMonitorVideoRecordStatistics = async (queryParam: any) => {
    const response = await pageMonitorVideoRecordStatistics(queryParam);
    if (response.code == 0) {
      setPageMonitorVideoRecordStatisticsDataState(response.data);
    }
  };
  useEffect(() => {
    loadPageMonitorVideoRecordStatistics({});
}, []);
  return (
    <PageContainer
      style={{ background: '#FFF' }}
      header={{
        //  title: (
        //   <Alert
        //     message="该功能目前处于试运行阶段，由于数据量较少，仍在不断完善中。如有任何问题或建议，请联系负责人房一以获取更多帮助，联系电话：13320207320"
        //     type="info"
        //   />
        //  ),
        breadcrumb: {
          items: [],
        },
        style: {
          paddingBlockEnd: 0,
        },
      }}
      content={
        <RcResizeObserver
          key="resize-observer"
          onResize={(size) => {
            setWidth(size.width);
          }}
        >
          <QueryFilter
            submitter={false}
            span={24}
            labelWidth="auto"
            split
            formRef={formRef}
            initialValues={{
              channelId: 'all', //渠道=全部
              levelId: 'all', //媒体=全部
              sourceIds: [], //媒体选择框=空
              // time: '最近90天',
              // releaseTimes: [moment().subtract(89, 'days'), moment()],
            }}
            onFinish={async (value) => {
              if (
                value.sourceIds.length == 0 &&
                value.channelId != 'all' &&
                value.channelId != 'clean'
              ) {
                value.sourceChannelIds = [value.channelId];
              } else {
                value.sourceChannelIds = [];
              }

              if (
                value.sourceIds.length == 0 &&
                value.levelId != 'all' &&
                value.levelId != 'clean'
              ) {
                value.sourceLevelIds = [value.levelId];
              } else {
                value.sourceLevelIds = [];
              }

              if (value.sourceIds != undefined && value.sourceIds.length !== 0) {
                let sourceIds = new Array();

                value.sourceIds.forEach((item: any[]) => {
                  const option = item[item.length - 1];
                  sourceIds.push(option);
                });
                value.sourceIds = sourceIds;
              }

              setQueryParamState({ ...queryParam, ...value });
              loadPageMonitorVideoRecordStatistics({ ...queryParam, ...value });
              actionRef.current?.reloadAndRest();
            }}
          >
            <ProForm.Group title="媒体">
              <ProFormRadio.Group
                name="channelId"
                radioType="button"
                options={[
                  { label: '全部', value: 'all' },
                  {
                    label: '抖音',
                    value: '8117112414994505',
                  },
                  { label: '快手', value: '8117112416043075' },
                ]}
                fieldProps={{
                  onChange: () => {
                    formRef.current?.setFieldValue('sourceIds', []);

                    let levelId = formRef.current?.getFieldValue('levelId');

                    if (levelId == 'clean') {
                      formRef.current?.setFieldValue('levelId', 'all');
                    }

                    getCascadersSource();
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormRadio.Group
                name="levelId"
                radioType="button"
                options={[
                  { label: '全部', value: 'all' },
                  { label: '市属媒体', value: '2000' },
                  { label: '区县媒体', value: '3000' },
                ]}
                fieldProps={{
                  onChange: () => {
                    formRef.current?.setFieldValue('sourceIds', []);

                    let channelId = formRef.current?.getFieldValue('channelId');

                    if (channelId == 'clean') {
                      formRef.current?.setFieldValue('channelId', 'all');
                    }

                    getCascadersSource();
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormCascader
                name="sourceIds"
                placeholder="选择媒体"
                fieldProps={{
                  options: optionsCascadersSourceData,
                  style: {
                    width: (width / 3) * 0.95,
                  },
                  multiple: true,
                  removeIcon: true,
                  allowClear: true,
                  showSearch: true,
                  maxTagCount: 'responsive',
                  showCheckedStrategy: Cascader.SHOW_CHILD,
                  onClear() {
                    formRef.current?.setFieldValue('channelId', 'clean');
                    formRef.current?.setFieldValue('levelId', 'clean');
                    getCascadersSource();
                    formRef.current?.submit();
                  },
                  onChange(value, selectOptions) {
                    let channelId = formRef.current?.getFieldValue('channelId');
                    let levelId = formRef.current?.getFieldValue('levelId');

                    if (channelId == 'clean' && levelId == 'clean') {
                      formRef.current?.setFieldValue('channelId', 'all');
                      formRef.current?.setFieldValue('levelId', 'all');
                    }

                    if (value.length > 0) {
                      formRef.current?.setFieldValue('channelId', 'clean');
                      formRef.current?.setFieldValue('levelId', 'clean');
                    }

                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
            <ProForm.Group title="发布时间">
              <ProFormRadio.Group
                name="time"
                radioType="button"
                options={[
                  { label: '今天', value: '今天' },
                  { label: '本月', value: '本月' },
                  { label: '上月', value: '上月' },
                  { label: '最近7天', value: '最近7天' },
                  { label: '最近60天', value: '最近60天' },
                  { label: '最近90天', value: '最近90天' },
                ]}
                fieldProps={{
                  onChange: () => {
                    const time = formRef.current?.getFieldValue('time');
                    if (time === '今天') {
                      formRef.current?.setFieldValue('releaseTimes', [moment(), moment()]);
                    } else if (time === '本月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month'),
                        moment().endOf('month'),
                      ]);
                    } else if (time === '上月') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().startOf('month').subtract(1, 'months'),
                        moment().endOf('month').subtract(1, 'months'),
                      ]);
                    } else if (time === '最近7天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(6, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近60天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(59, 'days'),
                        moment(),
                      ]);
                    } else if (time === '最近90天') {
                      formRef.current?.setFieldValue('releaseTimes', [
                        moment().subtract(89, 'days'),
                        moment(),
                      ]);
                    }
                    formRef.current?.submit();
                  },
                }}
              />
              <ProFormDateRangePicker
                name="releaseTimes"
                fieldProps={{
                  onChange(dates, dateStrings) {
                    formRef.current?.setFieldValue('time', ' ');
                    formRef.current?.submit();
                  },
                }}
              />
            </ProForm.Group>
          </QueryFilter>
        </RcResizeObserver>
      }
    >
      <ProTable<MonitorVideoData.VideoRecordPage>
        cardBordered
        actionRef={actionRef}
        columns={columns}
        request={async (params = {}) => {
          const response = await pageMonitorVideo({
            ...params,
            ...queryParam,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        search={false}
        editable={{
          type: 'multiple',
        }}
        rowKey="key"
        options={false}
        toolBarRender={() => [
          <>
            <div
              style={{
                marginTop: 21,
                marginLeft: 10,
              }}
            >
              <ProFormSwitch
                name="isViolation"
                label="只看问题"
                fieldProps={{
                  onChange: (checked) => {
                    setQueryParamState({ ...queryParam, isViolation: checked ? 1 : null });
                    formRef.current?.submit();
                  },
                }}
              />
            </div>
          </>,
        ]}
        toolbar={{
          search: {
            placeholder: '请输入文章标题搜索',
            allowClear: true,
            onSearch: (value: string) => {
              setQueryParamState({ ...queryParam, content: value });
              formRef.current?.submit();
            },
          },
        }}
        headerTitle={
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
          >
            {/* {pageMonitorVideoRecordStatisticsData &&
              pageMonitorVideoRecordStatisticsData.length > 0 && (
                <Segmented
                  name="segmented2"
                  key="label"
                  defaultValue={pageMonitorVideoRecordStatisticsData[0]?.label}
                  options={pageMonitorVideoRecordStatisticsData.map((item) => {
                    return {
                      label: (
                        <div>
                          <div> {item.label}</div>
                          <div>{item.value}</div>
                        </div>
                      ),
                      value: item.label,
                    };
                  })}
                />
              )} */}
            {pageMonitorVideoRecordStatisticsData &&
              pageMonitorVideoRecordStatisticsData.length > 0 && (
                <Descriptions
                  size="small"
                  layout="vertical"
                  bordered
                  column={
                    pageMonitorVideoRecordStatisticsData &&
                    pageMonitorVideoRecordStatisticsData.length
                  }
                  labelStyle={{color:'#CF1322'}}
                  className='description'
                >
                  {pageMonitorVideoRecordStatisticsData.map((item) => (
                    <Descriptions.Item label={item.label} style={{ textAlign: 'center' }}>
                      <span style={{ color: '#FF4D4F' }}>{item.value}</span>
                    </Descriptions.Item>
                  ))}
                </Descriptions>
              )}
          </div>
        }
      />
    </PageContainer>
  );
};

export default PageContainerMonitorVideo;
